<template>
  <div class="space-user-analyze">
    <a-card title="用户上传分析">
      <v-chart :option="options" style="height: 320px; max-width: 100%" :loading="loading" />
      <template #extra>
        <a-space>
          <a-segmented v-model:value="timeDimension" :options="timeDimensionOptions" />
          <a-input-search
            placeholder="请输入用户ID，则分析所有用户"
            style="min-width: 370px"
            enter-button="执行"
            allow-clear
            @search="doAnalyze"
            v-if="isAdmin"
          />
        </a-space>
      </template>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue'
import { getSpaceUserAnalyzeUsingPost } from '@/api/spaceAnalyzeController.ts'
import { message } from 'ant-design-vue'
import VChart from 'vue-echarts'
import 'echarts'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'

interface Props {
  queryAll?: boolean
  queryPublic?: boolean
  spaceId?: string
}

const props = withDefaults(defineProps<Props>(), {
  queryAll: false,
  queryPublic: false,
})

// 时间维度选项
const timeDimension = ref<'day' | 'week' | 'month' | 'year'>('day')
// 用户选项
const userId = ref<string>()
// 点击搜索时才改变 userId 的值
const doAnalyze = (value: string) => {
  userId.value = value
}
// 分段选择器组件的选项
const timeDimensionOptions = [
  {
    label: '日',
    value: 'day',
  },
  {
    label: '周',
    value: 'week',
  },
  {
    label: '月',
    value: 'month',
  },
  {
    label: '年',
    value: 'year',
  },
]

// 图标数据
// @ts-ignore
const dataList = ref<API.SpaceUsageAnalyzeResponse>([])
// 显示处于加载状态，进入页面就显示加载中
const loading = ref(true)
// 获取数据
const fetchData = async () => {
  const res = await getSpaceUserAnalyzeUsingPost({
    queryAll: props.queryAll,
    queryPublic: props.queryPublic,
    // @ts-ignore
    spaceId: props.spaceId,
    timeDimension: timeDimension.value,
    // @ts-ignore
    userId: userId.value,
  })
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    dataList.value = res.data.data ?? []
  } else {
    message.error('用户上传行为分析失败，' + res.data.message)
  }
  loading.value = false
}

// 图标操作选项
const options = computed(() => {
  // @ts-ignore
  const periods = dataList.value.map((item) => item.period) // 时间区间
  // @ts-ignore
  const counts = dataList.value.map((item) => item.count) // 上传数量

  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: periods, name: '时间区间' },
    yAxis: { type: 'value', name: '上传数量' },
    series: [
      {
        name: '上传数量',
        type: 'line',
        data: counts,
        smooth: true, // 平滑折线
        emphasis: {
          focus: 'series',
        },
      },
    ],
  }
})

/**
 * 参数改变时，就要触发函数，重新获取数据
 */
watchEffect(() => {
  fetchData()
})

/**
 * 判断当前用户是否为管理员
 */
const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser
const isAdmin = computed(() => {
  return loginUser?.userRole === 'admin'
})
</script>

<style scoped></style>
